import 'dart:async';

import 'package:avatar_glow/avatar_glow.dart';
import 'package:chatbot/manager/store_manager.dart';
import 'package:chatbot/page/chat_page.dart';
import 'package:chatbot/utils/colors.dart';
import 'package:flutter/material.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:provider/provider.dart';
import 'package:speech_to_text/speech_to_text.dart';
import 'package:speech_to_text/speech_to_text_provider.dart';

class ProviderDemoApp extends StatefulWidget {
  final SpeechToText speech;
  final SpeechToTextCallBack speechToTextCallBack;
  final SpeechToTextProvider speechProvider;

  ProviderDemoApp({required this.speech, required this.speechProvider, required this.speechToTextCallBack});

  @override
  State<ProviderDemoApp> createState() =>
      _ProviderDemoAppState(speech: speech, speechProvider: speechProvider,speechToTextCallBack: speechToTextCallBack);
}

class _ProviderDemoAppState extends State<ProviderDemoApp> {
  final SpeechToText speech;
  final SpeechToTextCallBack speechToTextCallBack;
  final SpeechToTextProvider speechProvider;

  _ProviderDemoAppState({required this.speech, required this.speechProvider, required this.speechToTextCallBack});

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<SpeechToTextProvider>.value(
      value: speechProvider,
      child: SpeechProviderExampleWidget(speechToTextCallBack: speechToTextCallBack,),
    );
  }
}

class SpeechProviderExampleWidget extends StatefulWidget {
  final SpeechToTextCallBack speechToTextCallBack;
  const SpeechProviderExampleWidget({Key? key,required this.speechToTextCallBack}) : super(key: key);

  @override
  SpeechProviderExampleWidgetState createState() =>
      SpeechProviderExampleWidgetState();
}

class SpeechProviderExampleWidgetState
    extends State<SpeechProviderExampleWidget> {
  String _currentLocaleId = '';
  final TextEditingController _textEditingController = TextEditingController();
  late List<LocaleName> localeList;
  var focusNode = FocusNode();
  late StreamSubscription<bool> keyboardSubscription;
  bool isKeyboardVisible = false;
  @override
  void initState() {
    super.initState();
    localeList = [
      LocaleName("zh-CN", "普通话"),
      LocaleName("en-US", "英语"),
      LocaleName("fr-FR", "法语"),
      LocaleName("ko-KR", "韩语"),
      LocaleName("ja-JP", "日语"),
      LocaleName("it-IT", "意大利语"),
      LocaleName("es-ES", "西班牙语"),
      LocaleName("ru-RU", "俄语"),
      LocaleName("uk-UA", "乌克兰语"),
      LocaleName("ar-SA", "阿拉伯语"),
      LocaleName("fa-IR", "波斯语")
    ];
    _currentLocaleId = StoreManager.getCurrentLocaleId(); //默认中文简体
    var keyboardVisibilityController = KeyboardVisibilityController();
    keyboardSubscription =
        keyboardVisibilityController.onChange.listen((bool visible) {
          debugPrint('Keyboard visibility update. Is visible: $visible');
          setState(() {
            isKeyboardVisible = visible;
          });
        });

  }

  @override
  Widget build(BuildContext context) {
    var speechProvider = Provider.of<SpeechToTextProvider>(context);
    if (speechProvider.isNotAvailable) {
      return const Center(
        child: Text('语音识别不可用, 到设置接界面打开麦克风权限.'),
      );
    }
    debugPrint("build!!!!!!!!!!");
    if(speechProvider.isListening) {

      String words = speechProvider.lastResult?.recognizedWords ?? '';
      _textEditingController.value = TextEditingValue(
          text: words,
          selection: TextSelection.fromPosition(
              TextPosition(
                  affinity: TextAffinity.downstream,
                  offset: words.length)));

    }
    return Container(
      height: isKeyboardVisible
          ? MediaQuery.of(context).size.height*3/4
          : MediaQuery.of(context).size.height / 2,
      child: Column(crossAxisAlignment: CrossAxisAlignment.center, children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: <Widget>[
            DropdownButton(
              style: const TextStyle(
                  color: Colors.white,
                  fontSize: 15,
                  fontWeight: FontWeight.w600),
              dropdownColor: ChatColors.commonLightColor,
              underline: Container(),
              onChanged: (selectedVal) => _switchLang(selectedVal),
              value: _currentLocaleId,
              items: localeList
                  .map(
                    (localeName) => DropdownMenuItem(
                  value: localeName.localeId,
                  child: Text(localeName.name),
                ),
              )
                  .toList(),
            ),
          ],
        ),
        Container(
          height: 12,
        ),
        Container(
          alignment: Alignment.center,
          margin: const EdgeInsets.fromLTRB(16, 0, 16, 0),
          height: 120,
          width: MediaQuery.of(context).size.width - 32,
          decoration: BoxDecoration(
            color: ChatColors.commonLightColor,
            borderRadius: const BorderRadius.all(Radius.circular(12.0)),
          ),
          child: TextField(
            controller: _textEditingController,
            style: const TextStyle(color: Colors.white),
            keyboardType: TextInputType.text,
            keyboardAppearance: Brightness.dark,
            focusNode: focusNode,
            maxLines: 6,
            // onChanged: (result) {
            //   setState(() {
            //     //更新发送按钮颜色
            //   });
            // },
            onSubmitted: (text) {},
            textInputAction: TextInputAction.done,
            decoration: InputDecoration(
                contentPadding: const EdgeInsets.fromLTRB(8, 0, 8, 2),
                border: InputBorder.none,
                hintText:
                speechProvider.isListening ? "正在倾听..." : "点击麦克风按钮开始说话...",
                hintStyle: const TextStyle(color: Colors.grey, fontSize: 14)),
          ),
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            InkWell(
              onTap: (){
                speechProvider.cancel();
                Navigator.pop(context);
              },
                child: const Text("取消",style: TextStyle(color: Colors.grey,fontSize: 15),)),
            Stack(
              alignment: Alignment.center,
              children: [
                AvatarGlow(
                  animate: speechProvider.isListening,
                  glowColor: Colors.white,
                  endRadius: 75.0,
                  duration: const Duration(milliseconds: 2000),
                  repeatPauseDuration: const Duration(milliseconds: 100),
                  repeat: true,
                  child: IconButton(
                    onPressed: () {
                      if (speechProvider.isListening) {
                        speechProvider.stop();
                      } else {
                        if (speechProvider.isAvailable && !speechProvider.isListening) {
                          speechProvider.listen(
                              partialResults: true, localeId: _currentLocaleId);
                        }
                      }
                    },
                    icon: Icon(speechProvider.isListening ? Icons.mic : Icons.mic_off,
                        color: Colors.white, size: 42),
                  ),
                ),
                Container(
                  margin: const EdgeInsets.only(top: 64),
                    child: Text(speechProvider.isListening ?"正在倾听":"点击开始说话",style:  TextStyle(color: Colors.grey.withOpacity(0.5),fontSize: 10),))
              ],
            ),
            InkWell(
              onTap: (){
                if(_textEditingController.text.trim().isEmpty){
                  speechProvider.cancel();
                  Navigator.pop(context);
                }else{
                  widget.speechToTextCallBack(_textEditingController.text.trim());
                  speechProvider.stop();
                  Navigator.pop(context);
                }
              },
                child: Text("发送",style: TextStyle(color: _textEditingController.text.isEmpty?Colors.grey:ChatColors.primaryColor,fontSize:  _textEditingController.text.isEmpty?16:17,fontWeight:  _textEditingController.text.isEmpty?FontWeight.normal:FontWeight.bold))),
          ],
        ),
        Expanded(
          child: Container(),
        )
      ]),
    );
  }

  void _switchLang(selectedVal) {
    setState(() {
      _currentLocaleId = selectedVal;
      StoreManager.setCurrentLocaleId(_currentLocaleId);
    });
    debugPrint(selectedVal);
  }
}
